const fs = require("fs");
const path = require("path");
const csso = require("csso");

function read(dir) {
  const files = [];
  const dirents = fs.readdirSync(dir, { withFileTypes: true });
  for (let dirent of dirents) {
    const fp = path.join(dir, dirent.name);
    if (dirent.isDirectory()) {
      files.push(...read(fp));
    } else if (dirent.name.endsWith(".css")) files.push(fp);
  }
  return files;
}

const files = read("./src");

let css = "";
for (let f of files) {
  try {
    const data = fs.readFileSync(f);
    css += data.toString();
  } catch (err) {
    console.error(err);
  }
}

const output = csso.minify(css, {
  filename: "./css/all.css",
  sourceMap: true,
});

fs.mkdirSync("./css");
fs.writeFileSync("./css/all.css", output.css);
fs.writeFileSync("./css/all.css.map", output.map.toString());

/*
  因为 ui-demo 编译工具的问题，只能引用 ui-demo 目录内部的 css 文件，
  所以编译后把 all.css 文件复制到 ui-demo/src 目录一份
*/
fs.copyFileSync("./css/all.css", "./ui-demo/src/all.css");
